package cn.pengpeng.day05.friends;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class CommonFriendsOne {
	
	public static class CommonFriendsOneMapper extends Mapper<LongWritable, Text, Text, Text>{
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			
			// A:B,C,D,F,E,O
			String[] split = value.toString().split(":");
			String user = split[0];
			String[] friends = split[1].split(",");
			
			for (String f : friends) {
				context.write(new Text(f), new Text(user));
			}
			
			
		}
		
		
	}
	
	public static class CommonFriendsOneReducer extends Reducer<Text, Text, Text, Text>{
		
		@Override
		protected void reduce(Text f, Iterable<Text> users, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			
			StringBuilder sb = new StringBuilder();
			for (Text u : users) {
				sb.append(u.toString()).append(",");
			}
			
			context.write(f, new Text(sb.toString()));
		}
		
		
	}
	
	
	public static void main(String[] args) throws Exception {

		Configuration conf = new Configuration(); // 会自动加载运行时classpath中的Hadoop配置文件

		Job job = Job.getInstance(conf);

		job.setJarByClass(CommonFriendsOne.class);

		job.setMapperClass(CommonFriendsOneMapper.class);
		job.setReducerClass(CommonFriendsOneReducer.class);

		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		Path path = new Path(args[1]);
		FileSystem fs = FileSystem.get(conf);
		if (fs.exists(path)) {
			fs.delete(path, true);
		}

		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, path);

		job.setNumReduceTasks(1);

		boolean res = job.waitForCompletion(true);
		System.exit(res ? 0 : 1);

	}
	

}
